// miniprogram/pages/addTodo/addTodo.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const db = wx.cloud.database();
const app = getApp();
const movements = db.collection('movements')
const recorder = wx.getRecorderManager()
Page({
  data: {
    soundSwitch: false,
    picSwitch: false,
    anonymousSwitch: true,
    locationSwitch: false,
    recordFinished: false,
    recordingDuration: 0,
    tempFilePaths: [],
    picUrls: [],
    soundUrl: '',
    input: '',
    location: null,
    locationName: ''
  },

  onLoad: function () {

  },

  ChooseImg: function () {
    let that = this;
    wx.chooseImage({
      count: 9, // 默认最多9张图片，可自行更改
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 1000
        })
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        let tempFilePath = res.tempFilePaths;
        that.setData({
          tempFilePaths: tempFilePath
        })
      }
    })
  },

  //预览图片
  PreviewImg: function (e) {
    let index = e.target.dataset.index;
    let that = this;
    //console.log(that.data.tempFilePaths[index]);
    //console.log(that.data.tempFilePaths);
    wx.previewImage({
      current: that.data.tempFilePaths[index],
      urls: that.data.tempFilePaths,
    })
  },
  //长按删除图片
  DeleteImg: function (e) {
    var that = this;
    var tempFilePaths = that.data.tempFilePaths;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          //console.log('点击确定了');
          tempFilePaths.splice(index, 1);
        } else if (res.cancel) {
          //console.log('点击取消了');
          return false;
        }
        that.setData({
          tempFilePaths
        });
      }
    })
  },

  bindInput: function (event) {
    this.setData({
      input: event.detail.text
    })
  },

  myEventListener: function (e) {
    console.log("上传的图片结果集合")
    console.log(e.detail.picsList)
  },
  //语音
  switch0Change: function (event) {
    this.setData({
      soundSwitch: event.detail.value
    })
  },
  onRecord: function (event) {
    recorder.onStop((res) => {
      console.log('recorder stop', res)
      if (res.duration < 1000) {
        this.setData({
          recording: '',
          soundSwitch: false
        })
        wx.showToast({
          title: '录音时间太短了',
          icon: 'none'
        })
      } else {
        this.setData({
          recordFinished: true,
          recording: res.tempFilePath,
          recordingDuration: res.duration
        })
      }
    })
    recorder.start({
      duration: 10000,
    })
    const countDown = this.selectComponent('.count-down');
    countDown.reset();
    countDown.start();
  },
  onRecordFinish: function (event) {
    //console.log(event)
    recorder.stop(res => {
      console.log(res)
    })
    const countDown = this.selectComponent('.count-down');
    countDown.pause();
  },
  //匿名
  switch1Change: function (event) {
    this.setData({
      anonymousSwitch: event.detail.value
    })
  },
  //图片
  switch2Change: function (event) {
    this.setData({
      picSwitch: event.detail.value,
      detailPic: ''
    })
  },
  //位置
  switch3Change: function (event) {
    if (event.detail.value) {
      wx.chooseLocation({
        success: res => {
          this.setData({
            location: res,
            locationName: res.name,
            locationSwitch: true
          })
        }
      })
    } else {
      this.setData({
        locationName: '',
        location: null,
        locationSwitch: false
      })
    }
  },

  changeLocation: function () {
    wx.chooseLocation({
      success: res => {
        console.log(res)
        this.setData({
          location: res,
          locationName: res.name
        })
      }
    })
  },

  createNonceStr: function () {
    var str = "",
      range = 20, //min
      arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    // 随机产生
    if (true) {
      range = Math.round(Math.random() * (36 - 20)) + 20;
    }
    for (var i = 0; i < range; i++) {
      var pos = Math.round(Math.random() * (arr.length - 1));
      str += arr[pos];
    }
    return str;
  },
  onClickLeft() {
    Dialog.confirm({
        title: '退出编辑',
        message: '确认要退出编辑吗？',
      })
      .then(() => {
        // on confirm
        wx.navigateBack()
      })
      .catch(() => {
        // on cancel
        wx.showToast({
          title: '留在编辑页',
          icon: 'none'
        });
      });
  },
  onClickRight() {
    if (this.data.input == '') {
      wx.showModal({
        title: '请不要发送空信息',
        cancelColor: 'cancelColor',
        success: res => {
          if (res.cancel)
            return
        }
      })
    } else if (this.data.locationSwitch && this.data.location.name == '') {
      wx.showToast({
        title: '请重新打开地址并在列表中选择地址哦',
        icon: 'none'
      })
      this.setData({
        locationSwitch: false
      })
      return
    } else {
      wx.showLoading({
        title: '正在提交',
      })
      var count = 0;
      var length = this.data.tempFilePaths.length;
      if (this.data.picSwitch && length == 0) {
        wx.showToast({
          title: '你还没添加图片呢！',
          icon: 'none'
        })
        return
      }
      var promiseArr = []
      if (this.data.soundSwitch&&this.data.recordFinished) {
        //上传录音
        var promise = new Promise((resolve, reject) => {
          var name = this.createNonceStr() + '.aac';
          wx.cloud.uploadFile({
            cloudPath: 'sound/' + name, //自定义云存储路径
            filePath: this.data.recording,
            success: res => {
              this.setData({
                soundUrl: res.fileID //更新data中的 fileID
              })
              resolve(res)
            },
            fail: res => {
              count++;
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传音频失败',
                showCancel: false,
                success: function (res) {}
              })
              reject(err)
            }
          })
        })
        promiseArr.push(promise)
      }
      for (var i = 0; i < length; i++) {
        //上传文件
        var promise = new Promise((resolve, reject) => {
          var imageUrl = this.data.tempFilePaths[i].split("/");
          var temp = imageUrl[imageUrl.length - 1].split(".");
          var type = temp[temp.length - 1];
          var picUrls = this.data.picUrls;
          var name = this.createNonceStr() + '.' + type;
          wx.cloud.uploadFile({
            cloudPath: 'pics/' + name, //自定义云存储路径
            filePath: this.data.tempFilePaths[i],
            success: res => {
              picUrls.push(res.fileID);
              this.setData({
                picUrls: picUrls //更新data中的 fileID
              })
              resolve(res)
            },
            fail: res => {
              count++;
              wx.hideToast();
              wx.showModal({
                title: '错误提示',
                content: '上传图片失败',
                showCancel: false,
                success: function (res) {}
              })
              reject(err)
            }
          });
        })
        promiseArr.push(promise)
      }
      Promise.all(promiseArr).then(res => {
        //console.log(promiseArr)
        //关键步骤：Promise.all()
        //传入Promise数组，当其中所有的Promise执行完后才会执行then()
        let time = this.getTimeStamp()
        var name = ''
        var head = ''
        if (this.data.anonymousSwitch) {
          name = app.globalData.randomName
          head = "cloud://wx-vn1hy.7778-wx-vn1hy-1303008862/timg.jpg"
        } else {
          name = app.globalData.name
          head = app.globalData.head
        }
        var movementId = movements.add({
          data: {
            createTime: time,
            username: name,
            userHead: head,
            anonymous: this.data.anonymousSwitch,
            text: this.data.input,
            soundEnable:this.data.soundSwitch,
            sound:this.data.soundUrl,
            soundDuration: this.data.recordingDuration,
            picEnable: this.data.picSwitch,
            picsList: this.data.picUrls,
            locationEnable: this.data.locationSwitch,
            location: this.data.location,
            like: 0,
            watch: 0,
            comment: 0,
            anonymous: this.data.anonymousSwitch
          }
        }).then(res => {
          console.log()
          wx.hideLoading()
          wx.reLaunch({
            url: '../index/index',
          })
        })
      })
    }
  },
  getTimeStamp: function () {
    return new Date().getTime()
  },
})